﻿using Autofac;
using CSRedis;
using DotNetCore.CAP.Dashboard;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Memory;
using MiniExcelLibs;
using SH.Common;
using SH.Common.CommonReturn;
using SH.Multitenant.API.Filters;
using SH.Multitenant.Application.IServices.IEmp;
using SH.Multitenant.Application.IServices.IUser;
using SH.Multitenant.Domain.RBAC;
using System.Reflection.PortableExecutable;

namespace SH.Multitenant.API.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class EmployeeController : ControllerBase
    {
        private readonly IEmpServices _empServices;
        private readonly IMemoryCache _cache;
        private readonly CSRedisClient _redis = AppService.AutofacContainer.Resolve<CSRedisClient>();
        public EmployeeController(IEmpServices empServices, IMemoryCache cache)
        {
            _empServices = empServices;
            _cache = cache;
        }
        /// <summary>
        /// 退出登录
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [LogActionFilter("Top", "退出登录")]
        public async Task LoginOut()
        {
            await _redis.DelAsync("tenantId");
        }
        /// <summary>
        /// 员工登录
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpPost]

        public async Task<IActionResult> EmpLogin(LoginRequestDTO request)
        {
            var result = await _empServices.EmpLogin(request);
            if (request == null)
            {
                return BadRequest();
            }
            if (string.IsNullOrEmpty(request.UName))
            {
                return BadRequest();
            }
            if (string.IsNullOrEmpty(request.UPwd))
            {
                return BadRequest();
            }
            if (result.Code == 200)
            {
                var token = result.Data!.Token;
                Response.Headers["token"] = token;
                Response.Headers["Access-Control-Expose-Headers"] = "token";
                //redis用户账号
                _redis.Set("uName", result.Data.UName);
                _redis.Set("tenantId", result.Data.TenantId);
                //存储用户token作为后台访问验证
                _cache.Set("token", token);
            }
            return Ok(result);
        }
        /// <summary>
        /// 多条件分页查询员工列表
        /// </summary>
        /// <param name="flag"></param>
        /// <param name="search"></param>
        /// <param name="pageSize"></param>
        /// <param name="pageIndex"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult ConditionQueryGetEmployees(int storeId, int flag, string? search, int pageSize, int pageIndex)
        {
            var result = _empServices.ConditionQueryGetEmployees(storeId, flag, search, pageSize, pageIndex);
            return Ok(result);
        }
        /// <summary>
        /// MiniExcel导出
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [LogActionFilter("Top", "MiniExcel导出")]
        public async Task<IActionResult> ExportExcel()
        {
            var list = _empServices.All.ToList();
            var memoryStream = new MemoryStream();
            await memoryStream.SaveAsAsync(list);
            memoryStream.Seek(0, SeekOrigin.Begin);
            return new FileStreamResult(memoryStream, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
            {
                FileDownloadName = "员工名单.xlsx"
            };
        }


        /// <summary>
        /// 员工添加
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        [LogActionFilter("Top", "员工信息添加")]
        public async Task<IActionResult> EmployeeAddAsync(EmployeeAddDTO dto)
        {
            var dateNow = DateTime.Now;
            dto.EmpId = dateNow.Ticks.ToString();
            dto.EntryTime = dateNow;
            var result = await _empServices.EmployeeAddAsync(dto);
            return Ok(result);
        }
        #region 唯一性验证
        /// <summary>
        /// 判断用户名是否唯一
        /// </summary>
        /// <param name="empName"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> EmpNameUnique(string empName)
        {
            ApiResult<bool> apiResult = new ApiResult<bool>();
            var result = await _empServices.EmpNameUnique(empName);
            apiResult.Success(result);
            return Ok(apiResult);
        }
        /// <summary>
        /// 判断手机号是否唯一
        /// </summary>
        /// <param name="tel"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> TelUnique(string tel)
        {
            ApiResult<bool> apiResult = new ApiResult<bool>();
            var result = await _empServices.TelUnique(tel);
            apiResult.Success(result);
            return Ok(apiResult);
        }
        #endregion

        /// <summary>
        /// 根据员工编号获取实体
        /// </summary>
        /// <param name="empId"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> GetEmpByEmpIdAsync(string empId)
        {
            var result = await _empServices.GetModelByConditionAsync(x => x.EmpId == empId);
            ApiResult<Employee> apiResult = new ApiResult<Employee>();
            apiResult.Success(result);
            return Ok(apiResult);
        }

        /// <summary>
        /// 员工信息修改
        /// </summary>
        /// <param name="employee"></param>
        /// <returns></returns>
        [HttpPost]
        [LogActionFilter("Top", "员工信息修改")]
        public async Task<IActionResult> UpdEmpInfoAsync(Employee employee)
        {
            var result = await _empServices.UpdEmpInfoAsync(employee);
            return Ok(result);
        }
        /// <summary>
        /// 根据员工获取角色编号
        /// </summary>
        /// <param name="empId"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> GetEmpRoleId(string empId)
        {
            var result = await _empServices.GetEmpRoleIdAsync(empId);
            ApiResult<int> apiResult = new ApiResult<int>();
            apiResult.Success(result);
            return Ok(apiResult);
        }
    }
}
